import datetime
import sys
import os

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','modules')))
import mods


def index(req):
	web = mods.Web(req)

	dbConnection = mods.GetDBConnection()
	cursor = dbConnection.cursor()

	id = web.GetData('id')
	addChild = web.GetData('add_child')
	addChildPostal = web.GetNumber('add_child_postal')
	edit = web.GetData('submit_edit')
	addChildError = ""
	todoDone = web.GetNumber('todo_done')
	addRequest = web.GetData('add_request')
	ticketDone = web.GetData('ticket_done')
	searchPostal = web.GetData('search_postal')
	setPostal = web.GetNumber('set_postal')

	updateID = web.GetData('update_id')

	location = mods.Location(id)


	if web.user.admin:
		#if updateID:
			#(status, message) = mods.UpdateLocationID(location.id, updateID)
			#if status:
				#id = updateID
				#location = mods.Location(id)
			#else:
				#mods.LogError(message)

		if addChild:
			children = addChild.split(',')
			for locationChild in children:
				location.AddChild(locationChild.strip())
			addChild = ''

		if addChildPostal:
			cursor.execute("""SELECT name, postal_street, postal_box
				FROM location_todo
				WHERE (id = %s)""", (addChildPostal, ))
			if cursor.rowcount:
				(newName, newStreet, newBox) = cursor.fetchone()
				location.AddChild(newName.strip(), newStreet.strip(), newBox.strip(), )
				todoDone = addChildPostal

		if edit:
			location.engName = web.GetData('eng_name')
			location.afrName = web.GetData('afr_name')
			location.postalCodeStreet = web.GetData('postal_street')
			location.postalCodeBox = web.GetData('postal_box')
			location.Save()

		if setPostal:
			location.postalCodeStreet = web.GetData('postal_street')
			location.postalCodeBox = web.GetData('postal_box')
			location.Save()

		if todoDone:
			cursor.execute("UPDATE location_todo SET done = TRUE where id = %s", (todoDone,))
			dbConnection.commit()

		if ticketDone:
			ticket = mods.Ticket(ticketDone)
			ticket.completeDate = datetime.datetime.now()
			ticket.completeBy = web.user.openID
			ticket.done = True
			ticket.Save()


	if web.user.active:
		if addRequest:
			ticket = mods.Ticket()
			ticket.reportBy = web.user.openID
			ticket.message = addRequest
			ticket.locationID = location.id
			ticket.Save()
			addRequest = ''


	web.Header()


	locationPath = []
	tempPath = location
	while tempPath.parent:
		tempPath = mods.Location(tempPath.parent)
		locationPath.append("""<a href="/locations/index.py?id=%s">%s</a>""" % (tempPath.id, tempPath.engName))
	locationPath.reverse()

	if locationPath:
		web.Write(" -> ".join(locationPath))
		web.Write("""<br /><br />""")

	if location.id:
		web.Write("""<b>%s</b><br />""" % (location.engName))

	web.Write("<br />")


	if location.id:
		web.Write("""<table class="data">""")
		if web.user.admin:
			web.Write("""<tr><th style="text-align: right;">Location ID</th><td style="text-align: left;">%s</td>""" % (location.id))
		web.Write("""<tr><th style="text-align: right;">English Name</th><td style="text-align: left;">%s</td>""" % (location.engName))
		web.Write("""<tr><th style="text-align: right;">Postal Code Street</th><td style="text-align: left;">%s</td>""" % (location.postalCodeStreet))
		web.Write("""<tr><th style="text-align: right;">Postal Code Box</th><td style="text-align: left;">%s</td>""" % (location.postalCodeBox))
		web.Write("""</table><br />""")


	if location.children:
		web.Write("""<table class="data">""")
		web.Write("""<tr><th>Name</th><th>More<br>Children</th><th>Postal<br>Street</th><th>Postal<br>Box</th></tr>""")
		for child in location.children:
			child = mods.Location(child)
			web.Write("""<tr>""")
			web.Write("""<td style="text-align:left;"><a href="/locations/index.py?id=%s">%s</a></td>""" % (child.id, child.engName))
			web.Write("""<td>%s</td>""" % (len(child.children)))
			web.Write("""<td>%s</td>""" % (child.postalCodeStreet))
			web.Write("""<td>%s</td>""" % (child.postalCodeBox))
			web.Write("""</tr>""")

		web.Write("""</table>""")



	if location.id:
		web.Write("""<br /><fieldset margin-left: 1em;"><legend>Request an update</legend>""")
		if web.user.active:
			web.Write("""<form action="/locations/index.py" method="post" name="add_request" >""")
			web.Write("""Problem : """)
			web.Write("""<input style="width: 70%%; margin: 0 0 1em 1em;" type="text" name="add_request" value="%s" />""" % (addRequest))
			web.Write("""<input type="hidden" name="id" value="%s" />""" % (location.id))
			web.Write("""<input type="submit" name="submit" value="Submit" />""")
			web.Write("""</form>""")

			#Outstanding tickets
			cursor.execute("SELECT id FROM tickets WHERE (location_id = %s) AND (done = FALSE) ORDER BY report_date DESC", (location.id,))
			if cursor.rowcount:
				web.Write("""<table class="grid">""")
				web.Write("""<tr><th>Date</th><th>User</th><th>Request</th><th>Done</th></tr>""")
				for record in cursor.fetchall():
					(ticketID, ) = record
					ticket = mods.Ticket(ticketID)
					web.Write("<tr>")
					web.Write("""<td style="text-align: left;">%s</td>""" % (ticket.reportDate.strftime("%Y-%m-%d %H:%M")))
					reporter = mods.User(ticket.reportBy)
					web.Write("""<td style="text-align: left;">%s</td>""" % (reporter.name))
					web.Write("""<td style="text-align: left;">%s</td>""" % (ticket.message))
					if web.user.admin:
						web.Write("""<td><a href="/locations/index.py?ticket_done=%s&id=%s">Done</a></td>""" % (ticket.id, location.id, ))
					else:
						web.Write("""<td></td>""")
					web.Write("</tr>")
				web.Write("</table>")

		else:
			web.Write("Please help opendb by logging in and reporting any problems with this location.")

		web.Write("""</fieldset><br />""")



		if web.user.admin:
			#Edit Location
			web.Write("""<div style="font-size: 0.8em;">""")
			web.Write("""<br /><fieldset class="form_table" style="float: left;"><legend>Edit Location</legend>""")


			web.Write("""<form action="/locations/index.py" method="post" name="add_child" >""")
			web.Write("""<b>Add Children</b>Comma separated<br />""")
			web.Write("""<input style="margin: 0 0 1em 1em;" type="text" name="add_child" value="%s" /><br />""" % (addChild))
			web.Write("""<input type="submit" name="submit" value="Submit" />""")
			web.Write("""<input type="hidden" name="id" value="%s" />""" % (location.id))
			web.Write("""</form><br /><hr /><br />""")



			#web.Write("""<form action="/locations/index.py" method="post" name="change_id" >""")
			#web.Write("""<b>Change Location ID</b><br />""")
			#web.Write("""<input style="margin: 0 0 1em 1em;" type="text" name="update_id" value="%s" /><br />""" % (location.id))
			#web.Write("""<input type="submit" name="submit" value="Submit" />""")
			#web.Write("""<input type="hidden" name="id" value="%s" />""" % (location.id))
			#web.Write("""</form><br /><hr /><br />""")



			web.Write("""<form action="/locations/index.py" method="post" name="edit_location" >""")
			web.Write("""<table>""")
			web.Write("""<tr>""")
			web.Write("""<td>English Name</td>""")
			web.Write("""<td><input type="text" name="eng_name" value="%s" /></td>""" % (location.engName))
			web.Write("""</tr>""")

			web.Write("""<tr>""")
			web.Write("""<td>Afrikaans Name</td>""")
			web.Write("""<td><input type="text" name="afr_name" value="%s" /></td>""" % (location.afrName))
			web.Write("""</tr>""")

			web.Write("""<tr>""")
			web.Write("""<td>Postal Code Street</td>""")
			web.Write("""<td><input type="text" name="postal_street" value="%s" /></td>""" % (location.postalCodeStreet))
			web.Write("""</tr>""")

			web.Write("""<tr>""")
			web.Write("""<td>Postal Code Box</td>""")
			web.Write("""<td><input type="text" name="postal_box" value="%s" /></td>""" % (location.postalCodeBox))
			web.Write("""</tr>""")

			web.Write("""<tr>""")
			web.Write("""<td></td>""")
			web.Write("""<td><input type="hidden" name="id" value="%s" />""" % (location.id))
			web.Write("""<input type="submit" name="submit_edit" value="Submit" /><td>""")
			web.Write("""</tr>""")

			web.Write("""</table>""")
			web.Write("""</form>""")
			web.Write("""</fieldset>""")



			web.Write("""<fieldset style="float: left; margin-left: 1em; display: block;"><legend>Postal Codes</legend>""")

			if not searchPostal:
				searchPostal = location.engName


			if searchPostal.isdigit():
				cursor.execute("""SELECT id, name, parent_name, postal_box, postal_street
					FROM location_todo
					WHERE (done = FALSE) AND ((postal_street = %s) OR (postal_box = %s)) ORDER BY name""",
					(searchPostal, searchPostal, ))
			else:
				cursor.execute("""SELECT id, name, parent_name, postal_box, postal_street
					FROM location_todo
					WHERE (done = FALSE) AND ((UPPER(name) LIKE %s) OR (UPPER(parent_name) LIKE %s)) ORDER BY name""",
					("%%%s%%" % searchPostal.upper(), "%%%s%%" % searchPostal.upper(), ))


			web.Write("""<form action="/locations/index.py" method="post" name="search" >""")
			web.Write("""<b>Search Postal Codes</b><br />""")
			web.Write("""<input style="margin: 0 0 1em 1em;" type="text" name="search_postal" value="%s" /><br />""" % (searchPostal))
			web.Write("""<input type="submit" name="submit" value="Submit" />""")
			web.Write("""<input type="hidden" name="id" value="%s" />""" % (location.id))
			web.Write("""</form><br /><hr /><br />""")


			web.Write("""<table class="grid">""")
			web.Write("""<tr><th>Name</th><th>Parent</th><th>Street</th><th>Box</th><th>Done</th></tr>""")
			for record in cursor.fetchall():
				(todoID, todoName, todoParent, todoBox, todoStreet) = record
				web.Write("<tr>")
				web.Write("""<td style="text-align: left;">%s</td>""" % (todoName))
				web.Write("""<td style="text-align: left;">%s</td>""" % (todoParent))
				web.Write("<td>%s</td>" % (todoStreet))
				web.Write("<td>%s</td>" % (todoBox))
				web.Write("""<td><a href="/locations/index.py?id=%s&add_child_postal=%s">Child</a> | """ % (location.id, todoID))
				web.Write("""<a href="/locations/index.py?id=%s&set_postal=1&postal_street=%s&postal_box=%s">Postal</a> | """ % (location.id, todoStreet, todoBox))
				web.Write("""<a href="/locations/index.py?id=%s&todo_done=%s">Done</a></td>""" % (location.id, todoID))
				web.Write("</tr>")
			web.Write("</table>")
			web.Write("""<br />""")
			web.Write("""</fieldset>""")


			web.Write("""</div>""")
			web.Write("""<br style="clear: both;"/>""")




	web.Write("""<br />""")

	web.Footer()


